#include "translator.h"
#include <locale>
#include <iostream>
#include "../lexical_cast/lexical_cast.h"

namespace umtl
{
	//////////////////////////////////////////////////////////////////////////
	//

	std::string translator::_appId = "E89E5D8AAE4C692D3B6FD844E296C5DB4A422BC1";

	//////////////////////////////////////////////////////////////////////////
	//

	translator::e_lang translator::detect( std::string & text )
	{
		boost::asio::ip::tcp::iostream http_stream( "api.microsofttranslator.com", "http" );

		http_stream << "GET /V2/Http.svc/Detect?" 

					<< "appId=" << _appId
					<< "&text=" << to_utf8(text)

					<< "\r\n" << std::flush;
		
		return parseResult( http_stream );
	}

	//////////////////////////////////////////////////////////////////////////
	//

	std::string translator::translate( std::string & text, translator::e_lang to, translator::e_lang from )
	{
		if( from.id() == e_lang::enum_end )
			from = detect( text );

		boost::asio::ip::tcp::iostream http_stream( "api.microsofttranslator.com", "http" );

		http_stream << "GET /V2/Http.svc/Translate?"

					<< "appID="	<< _appId
					<< "&text="	<< to_utf8(text)
					<< "&from="	<< from.string()
					<< "&to="	<< to.string()

					<< "\r\n" << std::flush;

		return parseResult( http_stream );
	}

	//////////////////////////////////////////////////////////////////////////
	//

	std::string translator::parseResult( boost::asio::ip::tcp::iostream & http_stream )
	{
		std::string str;
		std::string line;

		while ( std::getline( http_stream, line ) )
			str = str + "\n" + line;

		wchar_t * tmp = new wchar_t[str.length()+1];

		memset( tmp, 0, str.length()+1 );

		MultiByteToWideChar( CP_UTF8, 0, str.c_str(), str.length()+1, tmp, str.length() + 1 );

		std::wstring wresult = tmp;

		delete [] tmp;

		size_t result_idx = wresult.find( L">" )+1;

		wresult = wresult.substr( result_idx, wresult.rfind( L"<" ) - result_idx );

		return lexical_cast<std::string>(wresult);
	}

	//////////////////////////////////////////////////////////////////////////
}